package com.example.concurrent.example.atomic;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author    lingchen
 * Email     838878458@qq.com
 * Time      2018/8/1
 * Function  ...
 */
@Slf4j
public class AtomicIntegerTest {
    /**
     * 执行的并发数
     */
    public static final int MAX_CLIENT = 50000;
    /**
     * 最大可运行的线程数
     */
    public static final int MAX_THREAD = 200;

    public static AtomicInteger integer = new AtomicInteger();

    public static void main(String[] args) throws Exception {
        /**
         * 线程池
         */
        ExecutorService service = Executors.newCachedThreadPool();
        /**
         * 信号
         */
        Semaphore semaphore = new Semaphore(MAX_THREAD);
        /**
         * 计数
         */
        CountDownLatch countDownLatch = new CountDownLatch(MAX_CLIENT);
        for (int i = 0; i < MAX_CLIENT; i++) {
            service.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        service.shutdown();
        log.info("运行结果:{}", integer.get());
    }

    public static void add() {
        integer.incrementAndGet();
    }
}
